/*
	flad : Copyright 2010 Dale J Williams

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package lads.flad.utils {
	
	import lads.flad.load.LoadManager;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	
	/**
	 * AssetLoader: parses engineDJW asset XML into load manager and loads
	 * @author Dale J Williams
	 * @version 1.0
	 */
	public class AssetLoader {
		
		static private var _onComplete	:Function;
		static private var _loader		:LoadManager;
		static private var _path		:String;
		static private var _xml			:XML;
		static private var _url			:String;
		static private var _prefix		:String;
		
		/// loads a settings XML file, all @file assets within
		static public function load($assetsXMLorURL:Object, $loader:LoadManager, $onComplete:Function=null, $prefix:String=null):void {
			_loader = $loader;
			_onComplete = $onComplete;
			_prefix = $prefix || "";
			
			if ($assetsXMLorURL is String) {
				_url = $assetsXMLorURL as String;
				loadXML();
			} else if ($assetsXMLorURL is XML) {
				_xml = $assetsXMLorURL as XML;
				loadAssets();
			}
		}
		
		static private function loadXML():void {
			_loader.addToCue(_url, "assetsXML");
			_loader.onComplete = loadXMLComplete;
			_loader.load();
		}
		
		static private function loadXMLComplete():void {
			_xml = _loader.getXML("assetsXML");
			loadAssets();
		}
		
		static private function loadAssets():void {
			_path = String(_xml.path) || "";
			var nodeName:String;
			var fileName:String;
			for each(var node:XML in _xml..@file) {
				node = node.parent();
				fileName = _path + node.@file;
				nodeName = _prefix + (node.@name || node.@file);
				if (node.@streaming != "true")
					_loader.addToCue(fileName, nodeName);
			}
			_loader.onComplete = loadComplete;
			_loader.load();
		}
		
		static private function loadError(e:IOErrorEvent):void {
			throw new Error("Asset Loader could not load assets XML from " + _url);
		}
		
		static private function loadComplete():void {
			if (_onComplete != null) _onComplete();
		}
		
		static public function get xml():XML { return _xml; }
		
	}

}